Qt.include("sha1.js")
Qt.include("oauth.js")
Qt.include("HttpAccess.js")
Qt.include("../Util/Database.js")


//TwitterへのアクセスURL
var URL_FRIEND_TIMELINE = "http://api.twitter.com/1/statuses/home_timeline.xml";
var URL_MENTIONS = "http://api.twitter.com/1/statuses/mentions.xml";
//発言
var URL_UPDATE = "http://api.twitter.com/1/statuses/update.xml";
var URL_DELETE = "http://api.twitter.com/1/statuses/destroy/%s.xml";
//DM
var URL_DM = "http://api.twitter.com/1/direct_messages.xml";
var URL_DM_SEND = "http://api.twitter.com/1/direct_messages/new.xml";
//フォローしてる/されてる
var URL_FRIENDS_IDS = "http://api.twitter.com/1/friends/ids.xml"
var URL_FOLLOWERS_IDS = "http://api.twitter.com/1/followers/ids.xml"
var URL_USERS_LOOKUP = "http://api.twitter.com/1/users/lookup.xml"
//お気に入り
var URL_FAVORITS = "http://api.twitter.com/1/favorites.xml";
var URL_FAVORITS_REQUEST_CREATE = "http://api.twitter.com/1/favorites/create/%s.xml";
var URL_FAVORITS_REQUEST_DESTROY = "http://api.twitter.com/1/favorites/destroy/%s.xml";
//フォローする
var URL_FRIENDSHIP_REQUEST_CREATE = "http://api.twitter.com/1/friendships/create.xml";
var URL_FRIENDSHIP_REQUEST_DESTROY = "http://api.twitter.com/1/friendships/destroy.xml";

//ユーザー情報
var URL_USER_INFO = "http://api.twitter.com/1/users/show.xml";
var URL_USER_TIMELINE = "http://api.twitter.com/1/statuses/user_timeline.xml";
//リスト
var URL_LISTS_LISTS = "http://api.twitter.com/1/lists.xml";
var URL_LISTS_SUBSCRIPTIONS = "http://api.twitter.com/1/lists/subscriptions.xml";
var URL_LISTS_STATUES = "http://api.twitter.com/1/lists/statuses.xml";
var URL_LISTS_POST_MEMBERS = "http://api.twitter.com/1/%s/%s/members.xml";
//検索
var URL_SEARCHS_LIST = "http://twitter.com/saved_searches.xml";
var URL_SEARCHS_STATUES = "http://search.twitter.com/search.atom";
var URL_SEARCHS_ADD_QUERY = "http://twitter.com/saved_searches/create.xml";
//リツイート
var URL_RETWEETS_TO_ME = "http://api.twitter.com/1/statuses/retweeted_to_me.xml";
var URL_RETWEETS_BY_ME = "http://api.twitter.com/1/statuses/retweeted_by_me.xml";
var URL_RETWEETS_OF_ME = "http://api.twitter.com/1/statuses/retweets_of_me.xml";
var URL_RETWEETS = "http://api.twitter.com/1/statuses/retweet/";
var URL_RETWEETS2 = ".xml";
//特定のつぶやき
var URL_SHOW_STATUS = "http://twitter.com/statuses/show.xml";


//アプリの認証キー
//rewit q
var _consumerSecret = "EBvNCTFA8C3p3DoOm39wwtGfgxO53m7G9k8WgZIe4XU";
var _consumerKey = "DlEc1ybVZ151JAhCXK3w";

//一時保存
var _token = "";

//ユーザーの認証情報
var _accessToken = "";
var _accessTokenSecret = "";
var _accessScreenName = "";
var _accessUserId = "";


//設定
var _source = "Rewit";
var _count = 30;


function func() {
    getAuthorizationLink();
    return "exec"
}

//ユーザー情報を取得する
function getAuthUserName(){
    checkAuthInfo();
    var ret = _accessScreenName;
    if(ret.length === 0){
        ret = "None"
    }

    return ret
}


//認証情報の状態を確認する
function checkAuthInfo(){
    var ret = false;

    //内容の確認
    if((_accessToken.length === 0)
            || (_accessTokenSecret.length === 0)){
        //ない

        //DBから読み込み
        _accessToken = readData(SETTING_KEY_ACCESS_TOKEN);
        _accessTokenSecret = readData(SETTING_KEY_ACCESS_TOKEN_SECRET);
        _accessScreenName = readData(SETTING_KEY_ACCESS_SCREEN_NAME);
        _accessUserId = readData(SETTING_KEY_ACCESS_USER_ID);

        if(_accessToken === undefined)          _accessToken = "";
        if(_accessTokenSecret === undefined)    _accessTokenSecret = "";
        if(_accessScreenName === undefined)     _accessScreenName = "";
        if(_accessUserId === undefined)         _accessUserId = "";

        if((_accessToken.length === 0)
                || (_accessTokenSecret.length === 0)){
            //ない
            _accessToken = "";
            _accessTokenSecret = "";
        }else{
            ret = true;
        }
    }else{
        //ある
        ret = true;
    }

    //ログ
    outputDebugAuthInfo();

    return ret;
}

//認証情報を保存する
function saveAuthInfo(token, token_secret, screen_name, id){

    if(token.length === 0 || token_secret.length === 0){
    }else{
        saveData("ACCESS_TOKEN", token);
        saveData("ACCESS_TOKEN_SECRET", token_secret);
        saveData("ACCESS_SCREEN_NAME", screen_name);
        saveData("ACCESS_USER_ID", id);
    }
}

//認証情報を削除する
function clearAuthInfo(){
    _accessToken = "";
    _accessTokenSecret = "";
    _accessScreenName = "";
    _accessUserId = "";
    saveData("ACCESS_TOKEN", _accessToken);
    saveData("ACCESS_TOKEN_SECRET", _accessTokenSecret);
    saveData("ACCESS_SCREEN_NAME", _accessScreenName);
    saveData("ACCESS_USER_ID", _accessUserId);
}

//認証情報をデバッグ出力
function outputDebugAuthInfo(){
//    console.log("OAuth info");
//    console.log(" token:" + _accessToken);
//    console.log(" secret:" + _accessTokenSecret);   //log
//    console.log(" name:"+_accessScreenName);
//    console.log(" id:" + _accessUserId);
}



//認証用のURLを取得する
function startOAuth(){

    var accessor = {
        consumerSecret: _consumerSecret, /*this.consumer.consumerSecret,*/
        tokenSecret: ''
    };

    var message = {
        method: "GET",
        action: "http://twitter.com/oauth/request_token",
        parameters: {
            oauth_signature_method: "HMAC-SHA1",
            oauth_consumer_key: _consumerKey//this.consumer.consumerKey
        }
    };

    OAuth.setTimestampAndNonce(message);
    OAuth.SignatureMethod.sign(message, accessor);
    var target = OAuth.addToURL(message.action, message.parameters);

    //Request Token/Request Token Secretを取り出して、PINを取得するためのURLを作成
    requestHttp('' , 'GET', target , true, saveTokenAndGetPIN);

    return target;
}

//取得したRequest Token/Request Token Secretを保存してかつブラウザを開く
//コールバック
function saveTokenAndGetPIN(object)
{
    var url = object.responseText;
    var datas = url.split("&");
    if(datas.length === 0){
    }else{
        url = "http://twitter.com/oauth/authorize" + "?" + datas[0];

        datas = datas[0].split("=");
        if(datas.length < 1){
            _token = "";
        }else{
            _token = datas[1];
        }
    }

    if(_token.length === 0){
        //失敗
    }else{
        //ブラウザアクセス
//        console.log(url);
        Qt.openUrlExternally(url);
    }
}

var onAuthRequestCallBack = null;

//PINコードで認証する
function requestAuthorization(pin_code, on_func)
{
    if(_token.length === 0){
        //NG
    }else{
        var accessor = {
            consumerSecret: _consumerSecret,
            tokenSecret: ''//this.token_secret // Request Token Secret
            };

        var message = {
            method: "GET",
            action: "http://twitter.com/oauth/access_token",
            parameters: {
                oauth_signature_method: "HMAC-SHA1",
                oauth_consumer_key: _consumerKey,
                oauth_token: _token, // Request Token
                oauth_verifier: pin_code
                }
            };
        OAuth.setTimestampAndNonce(message);
        OAuth.SignatureMethod.sign(message, accessor);
        var target = OAuth.addToURL(message.action, message.parameters);
//        var options = {
//            type: message.method,
//            url: target,
//            success: function(d, dt) { /* 返り値からAccess Token/Access Token Secretを取り出す */ },
//        };

        // UIへのコールバック
        onAuthRequestCallBack = on_func;

        //認証
        requestHttp('' , 'GET', target , true, saveAccessTokenAndSecret);
    }
}

//認証結果のAccess Token/Access Token Secretを保存する
function saveAccessTokenAndSecret(object)
{
    var ret = false;
    var url = object.responseText;
    var datas = url.split("&");
    if(url.length === 0){
    }else if(datas.length === 0){
    }else{
        var items = null;

        var data = "aa";

//        console.log("url:" + url);

        for(var i=0; i<datas.length; i++){
            data = datas[i];
            if(data.indexOf("oauth_token_secret") === 0){
                items = data.split("=");
                _accessTokenSecret = items[1];
            }else if(data.indexOf("oauth_token") === 0){
                items = data.split("=");
                _accessToken = items[1];
            }else if(data.indexOf("screen_name") === 0){
                items = data.split("=");
                _accessScreenName = items[1];
            }else if(data.indexOf("user_id") === 0){
                items = data.split("=");
                _accessUserId = items[1];
            }else{
            }
            items = null;
        }

        //ログ
        outputDebugAuthInfo();

        //結果を保存する
        saveAuthInfo(_accessToken, _accessTokenSecret
                    , _accessScreenName, _accessUserId);

        ret = true;
    }

    //UIへのコールバック
    if(onAuthRequestCallBack !== null){
        onAuthRequestCallBack(ret);
        onAuthRequestCallBack = null;
    }
}


//シグネチャをつけたURLを作成する
function getSignedURL(method, api, content, callback) {

    var target = "";

    //認証情報を確認
    if(!checkAuthInfo()){
        //NG
    }else{
        var accessor = {
            consumerSecret: _consumerSecret,
            tokenSecret: _accessTokenSecret // Access Token Secret
        };

        var message = {
          method: method,
          action: api,
          parameters: {
            oauth_signature_method: "HMAC-SHA1",
            oauth_consumer_key: _consumerKey,
            oauth_token: _accessToken // Access Token
          }
        };

        // 送信するデータをパラメータに追加する
        for ( var key in content ) {
          message.parameters[key] = content[key];
        }
        OAuth.setTimestampAndNonce(message);
        OAuth.SignatureMethod.sign(message, accessor);
        target = OAuth.addToURL(message.action, message.parameters);
    }

    return target;
}


//Timelineの取得URLを作成
function getTimelineURL(page)
{
    var api = URL_FRIEND_TIMELINE;
    var content = {count: _count
                , page: page
                , include_rts: 1
                , exclude_replies: 0
                , include_entities: 1
                };
    var url = getSignedURL("GET", api, content, null);

    return url;
}

//特定のつぶやき
function getStatusShow(status_id)
{
    var api = URL_SHOW_STATUS;
    var content = {id: status_id
                , include_entities: 1
                };
    var url = getSignedURL("GET", api, content, null);
//    var api = URL_FRIEND_TIMELINE;
//    var content = {count: 1
//                , since_id: status_id
//                , include_rts: 1
//                , exclude_replies: 0
//                , include_entities: 1
//                };
//    var url = getSignedURL("GET", api, content, null);

    return url;
}

//MentionのURLを取得する
function getMentionURL(page)
{
    var api = URL_MENTIONS;
    var content = {count: _count
                , page: page
                , include_entities: 1
                };
    var url = getSignedURL("GET", api, content, null);

    return url;
}

//DMのURLを取得する
function getDirectMessageURL(page)
{
    var api = URL_DM;
    var content = {count: _count
                , page: page
                , include_entities: 1
                };
    var url = getSignedURL("GET", api, content, null);

    return url;
}

//リスト一覧のURLを取得する
function getListListsURL(type)
{
    var api = "";
    if(type === 0){
        api = URL_LISTS_LISTS;
    }else{
        api = URL_LISTS_SUBSCRIPTIONS;
    }
    var content = {screen_name: _accessScreenName
                };
    var url = getSignedURL("GET", api, content, null);

    return url;
}
//リストの内容のURLを取得する
function getListStatusURL(list_id, page)
{
    var api = URL_LISTS_STATUES;
    var content = {list_id: list_id
                , per_page: _count
                , page: page
                , include_entities: 1
                };
    var url = getSignedURL("GET", api, content, null);

    return url;
}





//Retweet to meの取得URLを作成
function getRetweetToMeURL(page)
{
    var api = URL_RETWEETS_TO_ME;
    var content = {count: _count
                , page: page
                , include_entities: 1
                };
    var url = getSignedURL("GET", api, content, null);

    return url;
}
//Retweet by meの取得URLを作成
function getRetweetByMeURL(page)
{
    var api = URL_RETWEETS_BY_ME;
    var content = {count: _count
                , page: page
                , include_entities: 1
                };
    var url = getSignedURL("GET", api, content, null);

    return url;
}

//Retweet of meの取得URLを作成
function getRetweetOfMeURL(page)
{
    var api = URL_RETWEETS_OF_ME;
    var content = {count: _count
                , page: page
                , include_entities: 1
                };
    var url = getSignedURL("GET", api, content, null);

    return url;
}




//FriendsのURLを取得する
function getFriendsFollowersIdsURL(is_friends)
{
    checkAuthInfo();

    var api = "";
    if(is_friends){
        api = URL_FRIENDS_IDS;
    }else{
        api = URL_FOLLOWERS_IDS;
    }
    var content = {screen_name: _accessScreenName
                };
    var url = getSignedURL("GET", api, content, null);

    return url;
}

//UserListのURLを取得する
//ids <num>,<num> カンマ区切りで一度に１００まで
function getUsersLookupURL(ids)
{
    var api = URL_USERS_LOOKUP;
    var content = {user_id: ids
                };
    var url = getSignedURL("GET", api, content, null);

    return url;
}
//UserListのURLを取得する
//screen_names <names>,<names> カンマ区切りで一度に１００まで
function getUsersLookupURLbyScreenName(screen_names)
{
    var api = URL_USERS_LOOKUP;
    var content = {screen_name: screen_names
                };
    var url = getSignedURL("GET", api, content, null);

    return url;
}

//UserのタイムラインのURLを取得する
function getUserTimelineURL(screen_name, page)
{
    var api = URL_USER_TIMELINE;
    var content = {screen_name: screen_name
                , count: _count
                , page: page
                , include_entities: 1
                };
    var url = getSignedURL("GET", api, content, null);

    return url;
}


//FavoritesのURLを取得する
function getFavoritesURL(page)
{
    var api = URL_FAVORITS;
    var content = {count: _count
                , page: page
                , include_entities: 1
                };
    var url = getSignedURL("GET", api, content, null);

    return url;
}




/////////////////////////////////////////////
//つぶやく
function sendTweet(tweet, in_reply_to, on_func)
{
    var api = URL_UPDATE;
    var content = {status: tweet
                    };
    if(in_reply_to.length !== 0) {
        content.in_reply_to_status_id = in_reply_to;
    }
    var url = getSignedURL("POST", api, content, null);

    //送信
    requestHttp('' , 'POST', url , true, on_func);
}
//Retweetする
function sendRetweet(id, on_func){
    var api = URL_RETWEETS + id + URL_RETWEETS2;
    if(id.length === 0){
        //NG
    }else{
        var url = getSignedURL("POST", api, null, null);
        //送信
        requestHttp('', 'POST', url, true, on_func);
    }
}
//Followする
function sendFriendshipRequest(screen_name, on_func){
    var api = URL_FRIENDSHIP_REQUEST_CREATE;
    var content = {screen_name: screen_name
                };
    if(screen_name.length === 0){
    }else{
        var url = getSignedURL("POST", api, content, null);
        //送信
        requestHttp('', 'POST', url, true, on_func);
    }
}
// Favする・解除
function sendFavoriteRequest(status_id, is_create, on_func){
    var api = "";

    if(status_id.length === 0){
    }else{
        if(is_create){
            api = URL_FAVORITS_REQUEST_CREATE.replace("%s", status_id);
        }else{
            api = URL_FAVORITS_REQUEST_DESTROY.replace("%s", status_id);
        }

        var url = getSignedURL("POST", api, null, null);
        //送信
        requestHttp('', 'POST', url, true, on_func);
    }
}
// Followする・解除
function sendFollowRequest(screen_name, is_create, on_func){
    var api = "";

    if(screen_name.length === 0){
    }else{
        var content = {screen_name: screen_name
                    };
        if(is_create){
            api = URL_FRIENDSHIP_REQUEST_CREATE;
        }else{
            api = URL_FRIENDSHIP_REQUEST_DESTROY;
        }

        var url = getSignedURL("POST", api, content, null);
        //送信
        requestHttp('', 'POST', url, true, on_func);
    }
}
